package com.eight.paper.admin.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.eight.common.annotation.Log;
import com.eight.common.constant.ExamConstants;
import com.eight.common.core.controller.BaseController;
import com.eight.common.core.domain.AjaxResult;
import com.eight.common.core.page.TableDataInfo;
import com.eight.common.core.redis.RedisCache;
import com.eight.common.enums.BusinessType;
import com.eight.common.utils.DateUtils;
import com.eight.common.utils.SecurityUtils;
import com.eight.common.utils.bean.BeanUtils;
import com.eight.common.utils.poi.ExcelUtil;
import com.eight.paper.admin.domain.ExamPaper;
import com.eight.paper.admin.domain.ExamPaperExaminee;
import com.eight.paper.admin.domain.model.*;
import com.eight.paper.admin.domain.model.enums.AnswerShowTypeEnum;
import com.eight.paper.admin.domain.model.enums.ComposeTypeEnum;
import com.eight.paper.admin.domain.model.enums.GradeStatusEnum;
import com.eight.paper.admin.service.IExamPaperExamineeService;
import com.eight.paper.admin.service.IExamPaperService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 考试试卷Controller
 * 
 * @author eight
 * @date 2023-10-31
 */
@Api(value = "考试管理", tags = "考试试卷")
@RestController
@RequestMapping("/paper/exam")
public class ExamExamController extends BaseController
{
    @Autowired
    private IExamPaperService examPaperService;
    @Autowired
    private IExamPaperExamineeService examPaperExamineeService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询考试试卷列表
     */
    @ApiOperation(value = "查询考试试卷列表")
    @PreAuthorize("@ss.hasPermi('paper:exam:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExamPaper examPaper)
    {
        startPage();
        Long deptId = SecurityUtils.getDeptId();
        examPaper.setDepts(deptId.toString());
        List<ExamPaperBody> list = examPaperService.selectExamineePaperList(examPaper);
        list.stream().forEach(e->{
            String key = String.format("%s:%s:%s", ExamConstants.TEMP_MARK,e.getId(),getUserId());
            if(redisCache.hasKey(key)){
                e.setGradeStatus(GradeStatusEnum.已阅卷.getCode());
            }else {
                key = String.format("%s:%s:%s", ExamConstants.TEMP_EXAM,e.getId(),getUserId());
                if(redisCache.hasKey(key)){
                    e.setGradeStatus(GradeStatusEnum.已答未阅卷.getCode());
                }else {
                    e.setGradeStatus(GradeStatusEnum.未答卷.getCode());
                }
            }
        });
        return getDataTable(list);
    }

    /**
     * 查询单个考生答卷列表
     */
    @ApiOperation(value = "查询单个考生答卷列表")
    @PreAuthorize("@ss.hasPermi('paper:exam:record')")
    @GetMapping("/record")
    public TableDataInfo record(@RequestParam(value = "paperName",required = false)String paperName,@RequestParam(value = "paperId",required = false)String paperId)
    {
        startPage();
        List<ExamPaperExamineeResponse> list = examPaperExamineeService.selectExamPaperExamineeRecord(getUserId(),paperName,paperId);
        return getDataTable(list);
    }

    /**
     * 导出考试试卷列表
     */
    @ApiOperation(value = "导出考试试卷列表")
    @PreAuthorize("@ss.hasPermi('paper:exam:export')")
    @Log(title = "考试试卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExamPaper examPaper)
    {
        List<ExamPaper> list = examPaperService.selectExamPaperList(examPaper);
        ExcelUtil<ExamPaper> util = new ExcelUtil<ExamPaper>(ExamPaper.class);
        util.exportExcel(response, list, "考试试卷数据");
    }

    /**
     * 导出考生答卷列表
     */
    @ApiOperation(value = "导出考生答卷列表")
    @PreAuthorize("@ss.hasPermi('paper:exam:exportExaminee')")
    @Log(title = "导出考生答卷列表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportExaminee")
    public void exportExaminee(HttpServletResponse response, ExamPaperExaminee examPaperExaminee)
    {
        List<ExamPaperExamineeResponse> list = examPaperExamineeService.selectExamPaperExamineeList(examPaperExaminee);
        ExcelUtil<ExamPaperExamineeResponse> util = new ExcelUtil<ExamPaperExamineeResponse>(ExamPaperExamineeResponse.class);
        util.exportExcel(response, list, "考生答卷数据");
    }

    /**
     * 获取考试试卷详细信息
     */
    @ApiOperation(value = "获取考试试卷详细信息")
    @PreAuthorize("@ss.hasPermi('paper:exam:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        Long userId = SecurityUtils.getUserId();
        String key = String.format("%s:%s:%s", ExamConstants.TEMP_EXAM,id,userId);
        if(redisCache.hasKey(key)){
//            ExamPaperReponseBody examPaper = examPaperService.selectExamPaperByIdAndUserId(id,userId);
//            return AjaxResult.success(examPaper);
            return AjaxResult.success((JSONObject)redisCache.getCacheObject(key));
        }else {
             ExamPaperReponseBody examPaper = examPaperService.selectExamPaperById(id, AnswerShowTypeEnum.False.getCode());
            //动态组卷，需初始化exam_paper_examinee表数据，记录试题信息
            /*if(ComposeTypeEnum.Dynamics.getCode().equals(examPaper.getComposeType())){
                List<QuestionOrder> groups = JSONArray.parseArray(JSON.toJSONString(examPaper.getGroups()),QuestionOrder.class);
                String qestionOrder = JSON.toJSONString(groups);
                examPaperService.initExamPaperExaminee(examPaper.getId(),userId.intValue(), DateUtils.getNowDate(),qestionOrder);
            }*/
            List<QuestionOrder> groups = JSONArray.parseArray(JSON.toJSONString(examPaper.getGroups()),QuestionOrder.class);
            String qestionOrder = JSON.toJSONString(groups);
            examPaperService.initExamPaperExaminee(examPaper.getId(),userId.intValue(), DateUtils.getNowDate(),qestionOrder);
            redisCache.setCacheObject(key,JSONObject.parseObject(JSON.toJSONString(examPaper)));
            return success((JSONObject)redisCache.getCacheObject(key));
        }
    }


    /**
     * 提交试卷
     */
    @ApiOperation(value = "提交试卷")
    @PreAuthorize("@ss.hasPermi('paper:exam:submitPaper')")
    @PostMapping(value = "/submitPaper/{id}")
    public AjaxResult submitPaper(@PathVariable("id") Integer paperId,@RequestBody JSONObject paper)
    {
        examPaperService.tempPaper(paperId,paper);
        examPaperService.submitPaper(paperId,paper);
        return success();
    }

    /**
     * 暂存试卷
     */
    @ApiOperation(value = "暂存试卷")
    @PreAuthorize("@ss.hasPermi('paper:exam:tempPaper')")
    @PostMapping(value = "/tempPaper/{id}")
    public AjaxResult tempPaper(@PathVariable("id") Integer paperId,@RequestBody JSONObject paper)
    {
        examPaperService.tempPaper(paperId,paper);
        return success();
    }

    /**
     * 考生获取答卷阅卷后详细信息
     */
    @ApiOperation(value = "考生获取答卷阅卷后详细信息")
    @PreAuthorize("@ss.hasPermi('paper:exam:getExamDetail')")
    @GetMapping(value = "/getExamDetail/{paperId}")
    public AjaxResult getExamDetail(@PathVariable("paperId") Integer paperId)
    {
        String key = String.format("%s:%s:%s", ExamConstants.TEMP_MARK,paperId,getUserId());
        if(redisCache.hasKey(key)){
            return AjaxResult.success((JSONObject)redisCache.getCacheObject(key));
        }
        return success(examPaperService.selectExamPaperById(paperId, AnswerShowTypeEnum.True.getCode()));
    }


    @ApiOperation("人脸识别")
    @PostMapping(value = "/face/{paperId}/{imageType}")
    public AjaxResult face(@RequestParam("file") MultipartFile file,@PathVariable("paperId") Integer paperId,@PathVariable("imageType") String imageType){
        boolean result;
        try {
            result = examPaperService.face(file,paperId,imageType);
            if(result){
                return success();
            }else {
                return AjaxResult.error("人脸识别失败");
            }
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

}
